import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * 编写程序，使用 FileChannel 和 CharBuffer 从不同的编码文件中正确的读取字符串
 * 已知的字符编码文件有：gbk.txt,utf8.txt,utf16.txt,utf32.txt
 */
public class Q2 {

    /**
     * 读取文本文件
     *
     * @param fn      文件名
     * @param charset 编码
     * @return 文本内容
     * @throws IOException IOException
     */
    public String readText(String fn, String charset) throws IOException {
        StringBuilder sb = new StringBuilder();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 4);  // Create byte buffer
        FileChannel in = new FileInputStream(fn).getChannel();

        int read = in.read(byteBuffer);
        while (read > 0) {
            byteBuffer.flip();  // Make buffer for read

            // Covert to char buffer by Charset
            CharBuffer cb = Charset.forName(charset).decode(byteBuffer);

            while (cb.hasRemaining()) {
                sb.append(cb.get());
            }

            byteBuffer.clear();  // Make buffer read for write
            read = in.read(byteBuffer);
        }

        return sb.toString();
    }

}
